package com.haohan.stock.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haohan.stock.domain.StockData;

@Service
public class RedisService {

	@Autowired
	private RedisTemplate<String, ?> redisTemplate;

	public boolean set(final String key, final String value) {
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
				connection.set(serializer.serialize(key), serializer.serialize(value));
				return true;
			}
		});
		return result;
	}

	public String get(final String key) {
		String result = redisTemplate.execute(new RedisCallback<String>() {
			@Override
			public String doInRedis(RedisConnection connection) throws DataAccessException {
				RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
				byte[] value = connection.get(serializer.serialize(key));
				return serializer.deserialize(value);
			}
		});
		return result;
	}
	/**
	 * 获取double类型数据
	 * @param key
	 * @return
	 */
	public double getDouble(final String key) {
		return Double.parseDouble(get(key));
	}
	/**
	 * 获取集合
	 * @param key
	 * @return
	 */
	public List<StockData> getList(final String key) {
		Gson gson = new Gson();
		return gson.fromJson(get(key), new TypeToken<List<StockData>>() {
		}.getType());
	}
}